package com.gelsanalyzer.application;

import java.awt.*;
import java.beans.*;
import java.net.*;

import javax.swing.*;

import org.apache.log4j.*;
import org.jdesktop.jdic.browser.*;

import com.gelsanalyzer.core.*;
import com.gelsanalyzer.mvc.controller.*;
import com.gelsanalyzer.mvc.view.*;

public class ReportViewerView extends AbstractViewPanel {
    private static final Logger log = Logger.getLogger(ReportViewerView.class);
    private WebBrowser webBrowser;
    private JPanel panelButtons;
    private JButton buttonViewGoals;
    private JButton buttonViewDepartments;
    
    public ReportViewerView() {
        try {
            initComponents();
            addComponents();
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    private void addComponents() {
        panelButtons.add(buttonViewDepartments);
        panelButtons.add(buttonViewGoals);
        this.add(panelButtons, BorderLayout.NORTH);
        this.add(webBrowser, BorderLayout.CENTER);
    }

    private void initComponents() throws Exception {
        webBrowser = 
            new WebBrowser();
        panelButtons = 
            new JPanel();
        buttonViewGoals = 
            new JButton(ActionFactory.getViewGoalReport());
        buttonViewDepartments = 
            new JButton(ActionFactory.getViewDepartmentsReport());
        webBrowser.addWebBrowserListener(new WebBrowserListener() {
            public void downloadStarted(WebBrowserEvent event) {;}
            public void downloadCompleted(WebBrowserEvent event) {;}
            public void downloadProgress(WebBrowserEvent event) {;}
            public void downloadError(WebBrowserEvent event) {;}
            public void documentCompleted(WebBrowserEvent event) {;}
            public void titleChange(WebBrowserEvent event) {;}
            public void statusTextChange(WebBrowserEvent event) {;}
            public void windowClose(WebBrowserEvent arg0)  {;}
        });
        
        this.setLayout(new BorderLayout(2,2));
        this.setPreferredSize(new Dimension(700, 500));
    }

    private void setBrowserURL(URL localUrl) {
        if ( localUrl == null ) {
            webBrowser.setContent("<html><h1>Error Loading Files</h1><p>Sorry "
                    + "for the inconvenience, but we are unable to load your "
                    + "report at this time.</p>");
        } else {
            webBrowser.setURL(localUrl);
        }
    }

    public void modelPropertyChange(PropertyChangeEvent event) {
        log .info("modelPropertyChange(PropertyChangeEvent "+event);
        if (event.getPropertyName().equals(IController.APP_VIEW_DEPARTMENTS_REP)) {
            setBrowserURL((URL)event.getNewValue());
        }
        else if(event.getPropertyName().equals(IController.APP_VIEW_GOALS_REP)) {
            setBrowserURL((URL)event.getNewValue());
        }
    }

}
